<template>
  <div v-if="permissionsLists(8)">
    <page-header :title="$t('m.Rental_order')" :has-return="false"></page-header>
    <div class="container">
      <div class="list_div">
        <div class="page_list_div">
          <el-form class="page_list_top" label-position="right">
            <el-form-item :label="$t('m.search_') + ':'" class="page_list_top">
              <el-input
                :placeholder="$t('m.Oders_Search_')"
                prefix-icon="el-icon-search"
                style="width:330px;"
                clearable
                v-model="params.search"
              />
            </el-form-item>

            <el-form-item
              :label="$t('m.Order_date') + ':'"
              class="page_list_top"
            >
              <el-date-picker
                style="width:246px;"
                v-model="params.rangeTime"
                :picker-options="datePickerOptions"
                :default-value="timeDefaultShow"
                type="daterange"
                :default-time="['00:00:00', '23:59:59']"
                value-format="timestamp"
                format="yyyy-MM-dd"
                range-separator="~"
                :start-placeholder="$t('m.start_date')"
                :end-placeholder="$t('m.end_date')"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              :label="$t('m.Order_List_PaymentStatus') + ':'"
              class="page_list_top"
            >
              <el-select
                v-model="params.paymentState"
                :placeholder="$t('m.pleaseChoose')"
                ref="select1"
                @change="searchClick('', 1)"
              >
                <el-option
                  v-for="item in payOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('m.Order_source') + ':'"
              class="page_list_top"
            >
              <el-select
                v-model="params.source"
                :placeholder="$t('m.pleaseChoose')"
                ref="select2"
                @change="searchClick('', 2)"
              >
                <el-option
                  v-for="item in sourceOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button class="reset_button" @click="searchClick('')">{{
                $t('m.search_')
              }}</el-button>
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button class="reset_button" @click="searchClick('1')">{{
                $t('m.refresh')
              }}</el-button>
            </el-form-item>
            <el-form-item class="page_list_top page_list_search" v-if="permissionsLists(236)">
              <el-button class="reset_button" @click="exportOrder">{{
                $t('m.exports')
              }}</el-button>
            </el-form-item>            
          </el-form>
        </div>
        <el-divider class="el_divider"></el-divider>
        <div class="el_table_div">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              :label="item.label"
              :name="item.value"
              v-for="item in stateOption"
              :key="item.value"
            ></el-tab-pane>
          </el-tabs>
          <el-table :data="page.records">
            <el-table-column
              prop="orderNo"
              :label="$t('m.Order_List_OrderID')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="ucode"
              :label="$t('m.User_ID')"
              min-width="130"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.ucode | strFormat }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.Order_source')" min-width="130">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.source | stateFormat(sourceOption) | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderTime"
              :label="$t('m.Order_date')"
              min-width="180"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.createTime | dateformat }} ~
                  {{ scope.row.endTime | dateformat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="useDuration"
              :label="$t('m.Order_List_Duration')"
              min-width="190"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.useDuration | formatSeconds | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="rentBranchName"
              :label="$t('m.Rent_from')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.rentBranchName | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="rentCabinetNo"
              :label="$t('m.Station_ID_form')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.rentCabinetNo | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="returnBranchName"
              :label="$t('m.Return_to')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.returnBranchName | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="returnCabinetNo"
              :label="$t('m.Station_ID_to')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.returnCabinetNo | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="pbNo"
              :label="$t('m.Order_List_Powerbank')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.pbNo | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderAmount"
              :label="$t('m.Order_amount')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.orderAmount | amountFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="realAmount"
              :label="$t('m.Payment_amount')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.realAmount | amountFormat }}
                </div>
              </template>
            </el-table-column>            
            <el-table-column
              prop="paymentState"
              :label="$t('m.Order_List_PaymentStatus')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{
                    scope.row.paymentState | stateFormat(payOption) | strFormat
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="state"
              :label="$t('m.Order_List_OrderStatus')"
              min-width="120"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.state | stateFormat(stateOption) | strFormat }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('m.Users_Details_Operation')"
              min-width="104"
              v-if="isArrayEqual([9, 11, 12, 169, 170, 171], permissionsLists)"
            >
              <template slot-scope="scope">
                <el-dropdown placement="bottom">
                  <img
                    src="@/assets/imgs/ic_operation.svg"
                    alt=""
                    class="dropdown_img"
                  />
                  <el-dropdown-menu
                    slot="dropdown"
                    style="white-space: nowrap !important;"
                  >
                    <el-dropdown-item
                      @click.native="detailClick(scope.row.orderNo)"
                      v-if="permissionsLists(9)"
                      >{{ $t('m.Details') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(1, scope.row)"
                      v-if="
                        scope.row.state == 3 &&
                          scope.row.realAmount - scope.row.refundAmount > 0 &&
                          userType == 1 &&
                          permissionsLists(11)
                      "
                      >{{ $t('m.Order_Refund') }}</el-dropdown-item
                    >
                    <!-- <el-dropdown-item
                      @click.native="orderClick(1, scope.row)"
                      v-if="
                        scope.row.state == 2 &&
                          userType == 1 &&
                          permissionsLists(12)
                      "
                      >{{ $t('m.Order_Deduct') }}</el-dropdown-item
                    > -->
                    <el-dropdown-item
                      @click.native="dialogClick(2, scope.row)"
                      v-if="
                        (scope.row.state == 1 || scope.row.state == 2) &&
                          userType == 1 &&
                          permissionsLists(170)
                      "
                      >{{ $t('m.Order_discounts') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(3, scope.row)"
                      v-if="
                        (scope.row.paymentState == 0 ||
                          scope.row.paymentState == 1) &&
                          (scope.row.state == 1 || scope.row.state == 2) &&
                          scope.row.realAmount > 0 &&
                          userType == 1 &&
                          permissionsLists(169)
                      "
                      >{{ $t('m.Order_freeCharge') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="orderClick(2, scope.row)"
                      v-if="
                        scope.row.state == 1 &&
                          userType == 1 &&
                          permissionsLists(171)
                      "
                      >{{ $t('m.Order_End_order') }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
            <emptydata
              slot="empty"
              v-if="!page.records || page.records.length == 0"
            />
          </el-table>
          <el-pagination
            background
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="page.size"
            :current-page.sync="page.current"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="5"
            :total="page.total"
            class="el_pagination"
            @size-change="changePageSize"
            @current-change="changePageNum"
            v-show="page.total > 0"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 结束订单/立即扣款 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="finishDialog"
        :title="
          dialogTypes == 2 ? $t('m.Order_End_order') : $t('m.Order_Deduct')
        "
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content">
          <div class="dialog_content2">
            {{
              dialogTypes == 2
                ? $t('m.Confirm_end_order')
                : $t('m.Order_Status_Deduct_confir')
            }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="finishDialog = false" class="cancel_btn">{{
            $t('m.cancel')
          }}</el-button>
          <el-button @click="endClick()" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>

      <!-- 免单/退款/优惠 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="freeDialog"
        :title="
          dialogTypef == 1
            ? $t('m.Order_Refund')
            : dialogTypef == 2
            ? $t('m.Order_discounts')
            : $t('m.Order_freeCharge')
        "
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content">
          <div class="dialog_content1">
            {{
              dialogTypef == 1
                ? $t('m.Actual_amount_paid')
                : $t('m.Order_amount')
            }}:
            <span class="dialog_content2">{{
              dialogTypef == 1
                ? orderRow.realAmount
                : orderRow.orderAmount | amountFormat
            }}</span>
          </div>
          <div
            class="dialog_content1"
            v-show="dialogTypef == 1 && orderRow.refundAmount > 0"
          >
            {{ $t('m.Order_Status_Refunded') }}:
            <span class="dialog_content2">{{
              orderRow.refundAmount | amountFormat
            }}</span>
          </div>
          <div class="dialog_content3" v-if="dialogTypef != 3">
            <div class="dialog_content3_title">
              {{
                dialogTypef == 1
                  ? $t('m.Order_refundAmount')
                  : $t('m.Order_Discount')
              }}:
            </div>
            <el-form style="width:100%">
              <el-form-item>
                <div id="box" class="currency">{{ $currency.symbol }}</div>
                <el-input
                  v-model="orderAmount"
                  clearable
                  :placeholder="$t('m.Please_enter')"
                  style="width:100%"
                  class="currency_input"
                  @input="changeAmount"
                  :style="widthStyle"
                >
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div
            class="dialog_content1"
            v-if="dialogTypef == 2 && orderAmount > 0"
          >
            {{ $t('m.Rental_amount_discount') }}:
            <span class="dialog_content2">{{
              (Number(
                dialogTypef == 1 ? orderRow.realAmount : orderRow.orderAmount
              ) -
                Number(orderAmount))
                | amountFormat
            }}</span>
          </div>
          <div class="dialog_content2">
            <img src="@/assets/imgs/ic_warn.svg" alt="" class="dialog_warn" />
            {{
              dialogTypef == 1
                ? $t('m.Refund_amount_explain')
                : dialogTypef == 2
                ? $t('m.After_setting_discount')
                : $t('m.After_setting_FOCorder')
            }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="freeDialog = false" class="cancel_btn">{{
            $t('m.cancel')
          }}</el-button>
          <el-button @click="amountsClick()" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import page from '@/mixins/page'
export default {
  mixins: [page],
  // inject: ['reload'],
  data () {
    return {
      datePickerOptions: {
        disabledDate (time) {
          let current_time = new Date().Format('yyyy-MM-dd') + ' 23:59:59' //时间日期为: ‘当前日期 23:59:59’
          let t = new Date(current_time).getTime() //‘当前日期 23:59:59’的时间戳
          return time.getTime() > t
        }
      },
      //请求参数
      params: {
        agentId: '', //	租借代理id
        branchId: '', //	租借网点id
        paymentState: '', //	支付状态: 0-未支付 1-已支付 2-免费 3-部分退款 4-全部退款
        purchaseMethod: '', //	购买方式: 0-直接购买 1-租借购买
        rangeTime: '', //	时间范围,示例值(1586966400000,1587966400000)
        report: '', //	故障单类型 0-待处理故障单 1-已处理故障单
        search: '', //	搜索字符串
        state: '', //	订单状态: 0-初始化 1-租借中 2-待支付 3-已完成 4-已取消 5-调查中 6-已退款 7-已报失 8-已购买
        uid: '', //	用户id
        source: '',
        cabinetType: ''
      },
      //支付状态
      payOption: [
        {
          value: '',
          label: this.$t('m.all')
        },
        {
          value: 0,
          label: this.$t('m.Order_Status_Unpaid')
        },
        {
          value: 1,
          label: this.$t('m.Payment_Status_Paid')
        },
        {
          value: 2,
          label: this.$t('m.Order_freeCharge')
        },
        {
          value: 3,
          label: this.$t('m.Payment_Status_Partialrefund')
        },
        {
          value: 4,
          label: this.$t('m.Order_Status_Refunded')
        }
      ],
      //订单状态
      stateOption: [
        {
          value: '99',
          label: this.$t('m.all')
        },
        {
          value: '1',
          label: this.$t('m.Order_Status_Renting')
        },
        {
          value: '2',
          label: this.$t('m.Order_Status_Unpaid')
        },
        {
          value: '5',
          label: this.$t('m.Order_Status_Surveying')
        },
        {
          value: '3',
          label: this.$t('m.Order_Status_Completed')
        }
      ],
      // 订单来源
      sourceOption: [
        {
          value: '',
          label: this.$t('m.all')
        },
        {
          value: '1',
          label: 'APP'
        },
        {
          value: '2',
          label: 'H5'
        }
      ],
      activeName: '99',
      finishDialog: false, //结束订单/扣款弹窗
      freeDialog: false, //免单/退款/优惠弹窗
      orderAmount: '', //退款/优惠金额
      dialogTypef: '', //免单/退款/优惠类型
      dialogTypes: '', //结束订单/扣款类型
      orderRow: '', //选中订单
      currencyWidth: '',
      userType: this.getUserType(), //用户类型
      permissionsIds: [] //权限id
    }
  },
  computed: {
    widthStyle () {
      return {
        '--currencyWidth': this.currencyWidth
      }
    }
  },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    if (!this.permissionsLists(8)) {
      return
    }
    this.timeDefaultShow = new Date()
    this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
    this.activeName = this.params.state == '' ? '99' : this.params.state
    this.getOrderLists()
  },
  mounted () {},
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    //获取货币宽度
    getWidth () {
      this.$nextTick(() => {
        let box = document.getElementById('box')
        this.currencyWidth = box.clientWidth + 14 + 'px'
      })
    },
    //获取订单列表
    getOrderLists () {
      this.$api.order.getOrderList(this.params, this.page).then(res => {
        if (this.$ok(res)) {
          this.page = res.data
        }
      })
    },
    // 搜索/重置
    searchClick (reset, e) {
      // 是否重置
      let size = this.page.size
      this.page = this.$options.data.call(this).page
      if (reset) {
        this.params = this.$options.data.call(this).params
        this.activeName = '99'
        this.timeDefaultShow = new Date()
        this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
        this.remPageNum()
      } else {
        this.page.size = size
        this.setPageNum(this.page.current, this.page.size, this.params)
      }
      this.$nextTick(() => {
        e ? this.$refs[`select${e}`].blur() : ''
      })
      this.getOrderLists()
    },
    // 每页数
    changePageSize (val) {
      this.page.current = 1
      this.page.size = val
      this.getOrderLists()
    },
    // 当前页
    changePageNum (val) {
      this.page.current = val
      this.getOrderLists()
    },
    //订单详情
    detailClick (orderNo) {
      this.setPageNum(this.page.current, this.page.size, this.params)
      // console.log(this.page)
      this.$router.push({ path: '/order/detail', query: { orderNo: orderNo } })
    },
    //切换tab
    handleClick (tab) {
      this.params.state = tab.name == '99' ? '' : tab.name
      this.remPageNum()
      this.page.current = 1
      this.page.records = []
      this.getOrderLists()
    },
    //退款/优惠/免单
    dialogClick (sum, item) {
      this.orderAmount = ''
      this.dialogTypef = sum
      this.orderRow = item
      // console.log(item);
      this.freeDialog = true
      this.getWidth()
    },
    //结束订单/立即扣款
    orderClick (sum, item) {
      this.dialogTypes = sum
      this.orderRow = item
      this.finishDialog = true
    },
    //金额限制
    changeAmount () {
      this.orderAmount = this.$check.amount(this.orderAmount)
      if (
        this.orderAmount >
          this.$check.preciseSubtract(
            this.orderRow.realAmount,
            this.orderRow.refundAmount
          ) &&
        this.dialogTypef == 1
      ) {
        this.orderAmount = this.$check.preciseSubtract(
          this.orderRow.realAmount,
          this.orderRow.refundAmount
        )
      }
      if (
        this.orderAmount > this.orderRow.orderAmount &&
        this.dialogTypef == 2
      ) {
        this.orderAmount = this.orderRow.orderAmount
      }
    },
    //操作按钮结果
    getRes (res) {
      if (this.$ok(res)) {
        this.$message.success(res.message)
        this.getOrderLists()
        this.freeDialog = false
        this.finishDialog = false
        this.$closeLoading()
      } else {
        this.$message.error(res.message)
        this.$closeLoading()
      }
    },
    //退款/优惠/免单确认按钮
    amountsClick () {
      if (this.dialogTypef == 1) {
        this.orderRefund()
      } else {
        this.orderState()
      }
    },
    //订单退款
    orderRefund () {
      let params = {
        amount: Number(this.orderAmount),
        orderNo: this.orderRow.orderNo,
        state:
          Number(this.orderAmount) -
            this.orderRow.realAmount -
            this.orderRow.refundAmount <
          0
            ? 2
            : 1
      }
      if (!this.orderAmount || this.orderAmount <= 0) {
        this.$message.info(this.$t('m.Please_enter_refund_amount'))
        return
      }
      // console.log(params)
      this.$openLoading()
      this.$api.order.orderRefund(params).then(res => {
        this.getRes(res)
      })
    },
    //优惠/免单
    orderState () {
      let params = {
        amount: this.dialogTypef == 2 ? Number(this.orderAmount) : '',
        orderNo: this.orderRow.orderNo,
        id: this.orderRow.id,
        state: this.dialogTypef
      }
      if (
        (!this.orderAmount || this.orderAmount <= 0) &&
        this.dialogTypef == 2
      ) {
        this.$message.info(this.$t('m.Please_enter_discount_amount'))
        return
      }
      // console.log(params)
      this.$openLoading()
      this.$api.order.orderState(params).then(res => {
        this.getRes(res)
      })
    },
    //结束订单/立即扣款
    endClick () {
      this.$openLoading()
      if (this.dialogTypes == 1) {
        this.$api.order.orderDeduction(this.orderRow.orderNo).then(res => {
          this.getRes(res)
        })
      } else {
        this.$api.order.orderEnd(this.orderRow.id).then(res => {
          this.getRes(res)
        })
      }
    },
    //导出订单
    exportOrder () {
      this.$openLoading()
      this.$api.order.getExportOrder(this.params).then(res => {
        window.downExcel(res, this.$t('m.Rental_order'))
        this.$closeLoading()
      })
    }, 
  }
}
</script>
<style lang="scss" scoped>
.currency {
  position: absolute;
  z-index: 6;
  left: 10px;
  color: #39404d;
  font-size: 14px;
  font-weight: 500;
}
.currency_input {
  ::v-deep .el-input__inner {
    padding-left: var(--currencyWidth) !important;
  }
}
</style>
